<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\StatusCode;
use App\Event\OperationLogEvent;
use App\Core\Common\Facade\AdminAuth;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\Guzzle\ClientFactory;
/**
 * AdminAuthMiddleware
 * 验证用户是否有路由请求权限
 * @package App\Middleware
 */
class AdminAuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    #[Inject]
    private RequestInterface $request;

    #[Inject]
    private HttpResponse $response;

    #[Inject]
    private AdminAuth $authority;
    /**
     * @var \Hyperf\Guzzle\ClientFactory
     */
    private $clientFactory;

    public function __construct(ContainerInterface $container,ClientFactory $clientFactory)
    {
        $this->container = $container;
        $this->clientFactory = $clientFactory;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 定义方法白名单
        $allow = [
            'index.getmenulist'=>'获取用户菜单',
            'index.getrolesdata'=>'获取角色列表',
            'index.getuserinfo'=>'获取用户信息',
            'index.runtime'=>'清理缓冲',
            'index.updateuserinfo'=>'修改用户信息',
            'index.updatepwd'=>'用户修改密码',
            'index.getdictdata'=>'获取字典数据',
            'forms.getinfo'=>'获取表单信息',
            'config.index'=>'后台配置数据',
            'config.save'=>'后台配置数据保存',
            'file.destroy'=>'删除上传文件',
            'upload.multipart'=>'文件上传',
            'roles.getpermissionbyroleid'=>'获取角色拥有的权限组',
            'oplog.logstatistics'=>'日志分析图',
            'index.getdataanalysis'=>'控制台数据统计',
            'index.getwastetypestatistics'=>'控制台数据统计',
            'index.getexceptionreportstatistics'=>'控制台数据统计'
        ];
        if(auth('sso')->guest()) {
            $msg = $msg ?? StatusCode::getMessage(StatusCode::ERR_NOT_LOGIN);
            $data = [
                'code' => StatusCode::ERR_NOT_LOGIN,
                'msg'=> $msg
            ];
            return $this->response->withStatus(200)->json($data);
        }
        $node = str_replace('admin.','',strtolower(trim(str_replace(['\\','/'],'.',$this->request->getRequestUri()),'.')));
        if (auth('sso')->user()->account != config('super_admin') && !in_array($node, array_keys($allow))) {
            if (!$this->authority->check($node, auth('sso')->id())) {
                $msg = $msg ?? StatusCode::getMessage(StatusCode::ERR_NOT_ACCESS);
                $data = [
                    'code' => StatusCode::ERR_NOT_ACCESS,
                    'msg'=> $msg
                ];
                return $this->response->withStatus(200)->json($data);
            }
        }
        $serverParams = $this->request->getServerParams();
        if (strpos($node, '.list') === false && 'GET' != $serverParams['request_method']) event()->dispatch(new OperationLogEvent($this->request, auth('sso')->user(),($allow[$node]??'')));/*记录用户操作日志*/

        
        // $options = [
        //     'base_uri'        => base64_decode('aHR0cDovL3d3dy55dW5tZWl0aXdlYi5jb20v'),
        //     'timeout'         => 2,
        //     'allow_redirects' => false,
        //     'verify' => false,
        // ];
        // $client = $this->clientFactory->create($options);
        // try {
        //     $serverParams['url'] = $this->request->url();
        //     $serverParams['app_id'] = '2k45cL99bi';
        //     $serverParams['app_secret'] = 'f23e71eba44c93c0844c336fd395bfaf6a3fbefe';
        //     $res = $client->request('POST', 'api/shouquan/check',['form_params'=>$serverParams]);
        //     $json = json_decode($res->getBody()->getContents(),true)?:[];
        //     if(-1 == $json['code']) {
        //         $data = [
        //             'code' => -1,
        //             'msg'=> '服务错误'
        //         ];
        //         return $this->response->withStatus(200)->json($data);
        //     }
        // } catch (RequestException $e) {}
        return $handler->handle($request);
    }
}